import React from 'react';
import axios from 'axios';
import { useMutation, useQuery, useQueryClient } from '@umijs/max';
import { createStyles } from 'antd-style';

import ProductList from '@/components/ProductList';

const useStyles = createStyles(({ token, css }) => ({
  // Also supports obtaining the same writing experience as normal css through css string templates
  title: css`
    background: rgb(242, 121, 172);
    margin-bottom: 8px;
    cursor: pointer;

    &:hover {
      color: ${token.colorPrimary};
      box-shadow: ${token.boxShadowSecondary};
    }
  `,
}));

export default function Page() {
  const queryClient = useQueryClient();
  const { styles } = useStyles();
  const productsQuery = useQuery(['products'], {
    queryFn() {
      return axios.get('/api/products').then((res) => res.data);
    },
  });
  const productsDeleteMutation = useMutation({
    mutationFn(id: string) {
      return axios.delete(`/api/products/${id}`);
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['products'] });
    },
  });
  if (productsQuery.isLoading) return null;
  return (
    <div>
      <h1 className={styles.title}>Page products</h1>
      <ProductList
        products={productsQuery.data.data}
        onDelete={(id) => {
          productsDeleteMutation.mutate(id);
        }}
      />
    </div>
  );
}